const inquirer = require('inquirer')
const fs = require('fs')
const utils = require('./utils')
const symbols = require('log-symbols')
// app 名字
let defaultScheme = ''
// 项目名
let defaultProject = ''

/**
 * 创建一个 config.json 文件，并赋初始值
 */
async function config() {
    try {
        await getProjectName()
        let answer = await inputParams()
        createFile(answer)
    } catch (error) {
        console.log(error)
    }
}

/**
 * 1、从当前路径下读取基本信息，获取 scheme project
 */
function getProjectName() {
    return new Promise((resolve, reject) => {
        fs.readdir(process.cwd(), (err, files) => {
            if (err) {
                reject(err)
            }
            files.forEach(file => {
                if (file.includes('.xcworkspace')) {
                    defaultScheme = file.split('.')[0]
                    defaultProject = file
                    return
                }
                if (file.includes('.xcodeproj')) {
                    defaultScheme = file.split('.')[0]
                    defaultProject = file
                }
            })
            resolve()
        })
    })
}

/**
 * 2、终端自定义
 */
function inputParams() {
    console.log('This utility will walk you through creating a package-ios.config.json')
    console.log('* 打包时必须有的文件')
    console.log('* 创建一次，后续使用默认值')
    console.log('* 创建之后可手动进行修改')
    console.log('* 打包之前，请确认该文件已正确填写')
    console.log(' ')

    const promptList = [
        {
            type: 'input',
            name: 'scheme',
            message: 'app 的名字？',
            default: defaultScheme
        },
        {
            type: 'input',
            name: 'project',
            message: '项目启动文件？',
            default: defaultProject
        },
        {
            type: 'list',
            name: 'configuration',
            message: '打包的环境?',
            choices: [
                'Debug',
                'Release'
            ]
        },
        {
            type: 'input',
            name: 'exportPath',
            message: '填写打包产物所存放的文件夹路径?',
            default: './'   
        }
    ]

    return new Promise((resolve, reject) => {
        inquirer.prompt(promptList)
            .then(answer => {
                resolve(answer)
            })
    })
}

/**
 *  3、生成 config.json 文件
 */
function createFile(answer) {
    fs.writeFile(utils.configJsonPath, JSON.stringify(answer, null, '\t'), err => {
        if (err) {
            console.log(err)
            process.exit(1)
        }
        console.log(symbols.success, `${utils.configJsonName} 文件已生成`)
    })
}

module.exports = config;